import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import layout from "../layout/index.vue";
import { getToken } from "../utils/auth";
import { Notify } from "vant";
const routes: Array<RouteRecordRaw> = [
    {
        path: "/",
        component: layout,
        children: [
            {
                path: "",
                name: "Home",
                component: () => import("../views/Home/index.vue")
            },
            {
                path: "power",
                name: "Power",
                component: () => import("../views/power/index.vue")
            },
            {
                path: "user",
                name: "User",
                component: () => import("../views/user/index.vue")
            }
        ]
    },
    {
        path: "/login",
        name: "Login",
        component: () =>
            import(/* webpackChunkName:'Login' */ "../views/login/index.vue")
    },
    {
        path: "/reg",
        name: "Reg",
        component: () =>
            import(/* webpackChunkName:'reg' */ "../views/reg/index.vue")
    },
    // 404
    {
        path: "/:pathMatch(.*)*",
        name: "404",
        redirect: "/"
    }
];

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
});

const blackList = ["/", "/power", "/reg"];

router.beforeEach(async (to: any, from: any, next: any) => {
    const hasToken = getToken();
    if (to.path != "/login") {
        if (hasToken) {
            next();
        } else if (blackList.includes(to.path)) {
            next();
        } else {
            Notify({ type: "primary", message: "请先登录后再操作" });
            next(`/login?redirect=${to.fullPath}`);
        }
    } else {
        next();
    }
});

router.afterEach((to: any, form: any) => {
    // const hasToken: any = getToken()
    // if (hasToken) {
    //   const userInfo: any = localStorage.getItem('userInfo')
    //   store.commit('user/M_setToken', hasToken)
    //   store.commit('user/M_setInfo', userInfo ? JSON.parse(userInfo) : {})
    // }
});

export default router;
